<template>
  <div>
    <main class="max-w-screen-2xl mx-auto">
      <div class="px-4 py-8 lg:flex" v-if="!isHome">
        <Menu class="hidden lg:block"></Menu>
        <div class="main-content-container flex-1">
          <div class="lg:flex lg:items-center lg:justify-between w-full border-b-slate-100 border-b-2 pb-1 mb-2">
            <h4 class="text-primary font-bold text-lg">
              {{ breadcrumbs[breadcrumbs.length - 1]?.label }}
            </h4>
            <el-breadcrumb class="hidden lg:block">
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item :to="item.url" v-for="(item, index) in breadcrumbs" :key="index">{{ item.label }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <slot />
        </div>
      </div>
      <slot v-if="isHome" />
    </main>
  </div>
</template>

<script setup>
// 获取路由的生成面包屑
const route = useRoute();
const router = useRouter();
const navList = useNav();
const breadcrumbs = useBreadcrumbs();
// 路由监听并判断是否为首页
const isHome = ref();
watchEffect(() => {
  isHome.value = route.path === "/";
  //面包屑
  const { cate_id } = route.params;
  let path = route.path;
  const parts = path.split("/");
  // 产品中心
  if (cate_id) {
    path = `/product/${cate_id}`;
  } else if (parts.length >= 3) {
    path = `/${parts[1]}/${parts[2]}`;
  }
  breadcrumbs.value = getBreadcrumbs(navList.value, path);
  if (parts.length > 1 && parts.length <= 3) {
    if (breadcrumbs.value.length == 1 && breadcrumbs.value.length <= 2 && breadcrumbs.value[0].url !== breadcrumbs.value[0].children[0].url) {
      router.push(breadcrumbs.value[0].children[0].url);
    }
  }
});
// 获取当前路由对应的菜单并返回数组
function getBreadcrumbs(navList, path) {
  let breadcrumbs = [];
  function findItem(items) {
    for (const item of items) {
      if (item.url === path) {
        breadcrumbs = [item];
        return true; // 停止递归
      }

      if (item.children && item.children.length > 0) {
        if (findItem(item.children)) {
          breadcrumbs.unshift(item);
          return true;
        }
      }
    }
    return false;
  }

  findItem(navList);
  return breadcrumbs;
}
</script>
<style scoped lang="scss"></style>
